package com.itheima.sh.user.service;

import com.itheima.sh.pojo.Order;
import com.itheima.sh.pojo.User;
import com.itheima.sh.response.OrderVO;
import com.itheima.sh.response.UserOrderVO;
import com.itheima.sh.user.client.OrderClient;
import com.itheima.sh.user.mapper.UserMapper;
import org.dozer.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class UserService  {

    @Autowired
    UserMapper userMapper;

    @Autowired
    Mapper mapper;

    @Autowired
    OrderClient orderClient;

    public User findUserById(String id) {
       return userMapper.selectByPrimaryKey(id);
    }

    public UserOrderVO findOrderByUserId(String username){
        // 1 参数校验
        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("参数非法");
        }

        // 2 查询用户的信息 User
        User user = userMapper.selectByPrimaryKey(username);
        if (user == null) {
            throw new RuntimeException("非法请求");
        }

        // 3 Feign 远程调用 Order微服务，获取订单的列表   List
        List<Order> orderList = orderClient.findOrderByUsername(user.getUsername());
        if (orderList == null) {
            orderList = new ArrayList<>();
        }

        // 4 封装返回的结果 Map
        // DTO 前端 --> 后端 传参  OrderDTO
        // VO  后端 --> 前端 响应结果  （1、信息安全， 2、降低网络传输带宽）
        // 新建一个 VO对象 （User，OrderList）
        UserOrderVO userOrderVO = new UserOrderVO();
        //userOrderVO.setUsername(user.getUsername()); 不推荐
        // 实体类 和 DTO/VO 之间转换， MapStruct, Dozer  java对象和O之间的转换
        // BeanUtils.copyProperties(user, userOrderVO);

        // 转换User
        mapper.map(user, userOrderVO);

        // 转换Order --> OrderVo
        List<OrderVO> orderVOList = new ArrayList<>();
        for (Order order : orderList) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            orderVOList.add(orderVO);
        }
        userOrderVO.setOrderList(orderVOList);



        return userOrderVO;
    }
}
